package com.smw.config;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.smw.myrealm.Myrealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //添加thymelaf集成shiro的插件
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier(value = "manager" )DefaultWebSecurityManager manager){

        ShiroFilterFactoryBean bean= new ShiroFilterFactoryBean();
        bean.setSecurityManager(manager);
        Map<String, String> map=new HashMap<String,String>();
//
        bean.setFilterChainDefinitionMap(map);
        bean.setLoginUrl("/user/toLogin");
        return bean;
    }
    @Bean(name = "manager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier(value = "myrealm") Myrealm myrealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        //装配上Realm
        securityManager.setRealm(myrealm);
        return securityManager;
    }
    @Bean(name = "myrealm")
    public Myrealm myRealm(){
        Myrealm myrealm=new Myrealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为md5
        hashedCredentialsMatcher.setHashAlgorithmName("SHA-256");
        //设置加密算法次数
        hashedCredentialsMatcher.setHashIterations(1024);
        //将自定义匹配添加进Realm中
        myrealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return myrealm;
    }

}
